<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="short icon" href="./favicon.ico">
    <!-- Import style -->
    <link rel="stylesheet" href="./libs/element-plus-2.4.2/index.css"/>
    <link rel="stylesheet" href="./style/index.css">
    <link rel="stylesheet" href="./style/common/style.css">
    <!-- Import Vue 3 -->
    <%--        <script src="//unpkg.com/vue@3"></script>--%>
    <script src="./libs/vue-3.37/vue.global.js"></script>
    <script src="./libs/element-plus-2.4.2/zh-cn.js"></script>
    <script src="./libs/element-plus-2.4.2/index.iife.min.js"></script>
    <!-- Import component library -->
    <script src="./libs/element-plus-2.4.2/index.full.js"></script>
    <title>图书管理系统</title>
</head>
<body>
<div id="app">
    <div class="root">
        <div class="container">
            <div class="login-form" v-if="isRegister" v-loading="isLoading">
                <h3 class="login-title">登录</h3>
                <el-form :model="loginForm" label-width="120px" label-position="left" :rules="loginRules"
                         @submit.prevent="userLogin" ref="loginFormRef">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="loginForm.username" placeholder="请输入用户名" name="username" clearable
                                  prefix-icon="User"/>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="loginForm.password" placeholder="请输入用户名" name="password"
                                  type="password" show-password clearable prefix-icon="Lock"/>
                    </el-form-item>
                    <el-form-item class="form-btn" label-width="0">
                        <el-button type="primary" native-type="submit">登录</el-button>
                        <el-button native-type="reset">重置</el-button>
                    </el-form-item>
                </el-form>
                <div class="tips">还没注册？
                    <el-link @click="switchForm">点击注册</el-link>
                </div>
            </div>
            <div class="register-form" v-else v-loading="isLoading">
                <h3 class="register-title">注册</h3>
                <el-form :model="registerForm" label-width="120px" label-position="left" :rules="registerRules"
                         @submit.prevent="userRegister" ref="registerFormRef">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="registerForm.username" placeholder="请输入用户名" name="username" clearable
                                  prefix-icon="User"/>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email" ref="emailFormItemRef">
                        <el-input v-model="registerForm.email" placeholder="请输入邮箱账号或完整地址" name="email"
                                  clearable
                                  prefix-icon="Message">
                            <template #append>
                                <el-select v-model="addressItem" placeholder="请选择邮箱地址" style="width: 150px"
                                           @blur="registerFormRef.validateField('email')" clearable>
                                    <el-option v-for="item in addressItems" :label="item.label" :value="item.value"/>
                                </el-select>
                            </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="registerForm.password" placeholder="请输入密码" name="password"
                                  type="password" show-password clearable prefix-icon="Lock"/>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="cPassword">
                        <el-input v-model="registerForm.cPassword" placeholder="请输入确认密码" name="cPassword"
                                  type="password" show-password clearable prefix-icon="Lock"/>
                    </el-form-item>
                    <el-form-item label="验证码" prop="verificationCode">
                        <div class="verificationCode-box">
                            <el-input v-model="registerForm.verificationCode" placeholder="请输入邮箱验证码"
                                      name="verificationCode" clearable prefix-icon="Promotion"
                                      class="verificationCode-input">
                            </el-input>
                            <el-button @click="getVerificationCode" :disabled="sendingTime!==0">
                                {{sendingTime!==0?`重发验证码(${sendingTime})`:"获取验证码"}}
                            </el-button>
                        </div>
                    </el-form-item>
                    <el-form-item class="form-btn" label-width="0">
                        <el-button type="primary" native-type="submit">注册</el-button>
                        <el-button native-type="reset" @click="addressItem=''">重置
                        </el-button>
                    </el-form-item>
                </el-form>
                <div class="tips">已有账号？
                    <el-link @click="switchForm">点击登录</el-link>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="module">
    import {pajax} from './utils/ajax.js'
    import {getCookie, setCookie} from "./utils/cookie.js"

    const {User, Lock, Message, Promotion, Loading} = ElementPlusIconsVue
    const {ElMessage} = ElementPlus
    const {createApp, ref, onMounted, h} = Vue
    const App = {
        setup() {
            const loginForm = ref({
                username: "",
                password: ""
            })
            const registerForm = ref({
                username: "",
                email: "",
                password: "",
                cPassword: "",
                verificationCode: ""
            })
            const addressItem = ref("")
            const addressItems = ref([
                {value: "@qq.com", label: "@qq.com"}
            ])
            const loginFormRef = ref()
            const registerFormRef = ref()
            const isRegister = ref(false)
            const isLoading = ref(true)
            const emailFormItemRef = ref()
            const loginRules = ref({
                username: [{required: true, message: "请输入用户名", trigger: "blur"}],
                password: [{required: true, message: "请输入密码", trigger: "blur"}]
            })
            const sendingTime = ref(0)
            const nameValidator = (rule, value, callback) => {
                let temp = value.match(/\w+/g);
                let [tempLength, totalLength] = [0, 0];
                if (temp !== null) {
                    temp.map((item) => {
                        tempLength += Math.round(item.length / 2);
                    });
                    totalLength = value.length - tempLength;
                } else
                    totalLength = value.length;
                if (!/^[\u4e00-\u9fa5_a-zA-Z0-9]+$/.test(value))
                    callback(new Error("用户名只能由中文、英文字母、数字以及下划线组成"));
                else if (!(1 <= totalLength && totalLength <= 20))
                    callback(new Error("用户名长度不能超过20个字符"));
                else callback();
            }
            const emailValidator = (rule, value, callback) => {
                if (value !== null && value !== "") {
                    if (!/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value) && !/\w+([-+.]\w+)*/.test(value)) {
                        callback(new Error("请检查邮箱地址是否正确"));
                    } else {
                        if (value.split("@")[0] == value) {
                            if (addressItem.value !== null && addressItem.value !== "")
                                callback()
                            else
                                callback(new Error("请输入或在右侧选择邮箱地址"));
                        } else if (value.split("@")[1].split(".")[0] === "qq") {
                            registerForm.value.email = value.split("@")[0]
                            addressItem.value = '@' + value.split("@")[1]
                            callback()
                        } else
                            callback(new Error("仅支持qq邮箱验证,更多邮箱验证待完善..."));
                    }
                } else
                    callback(new Error("请输入邮箱账号"));
            }
            const passwordValidator = (rule, value, callback) => {
                if (value !== null && value !== "") {
                    if (registerForm.value.cPassword !== registerForm.value.password) {
                        callback(new Error("两次密码不一致"));
                    } else
                        callback();
                } else
                    callback(new Error("请再次输入密码"));

            }
            const registerRules = ref({
                username: [{required: true, validator: nameValidator, trigger: "blur"}],
                email: [{required: true, validator: emailValidator, trigger: "blur"}],
                password: [{required: true, message: "请输入密码", trigger: "blur"}],
                cPassword: [{required: true, validator: passwordValidator, trigger: "blur"}],
                verificationCode: [{required: true, message: "请输入验证码", trigger: "blur"}]
            })
            onMounted(() => {
                setTimeout(() => {
                    isLoading.value = false
                }, 500)
            })
            const switchForm = () => {
                isLoading.value = true
                setTimeout(() => {
                    isLoading.value = false
                    isRegister.value = !isRegister.value
                }, 500)
            }
            // 登录ajax请求
            const userLogin = () => {
                loginFormRef.value.validate((valid, fields) => {
                    if (valid) {
                        pajax({
                            url: "login",
                            method: "GET",
                            params: {
                                username: loginForm.value.username,
                                password: loginForm.value.password
                            }
                        })
                            .then(res => {
                                if (res.code) {
                                    ElMessage.success("登陆成功")
                                    setTimeout(() => location.href = "./web/home.jsp", 500)
                                } else
                                    ElMessage.error(res.msg)
                            })
                            .catch(err => {
                                ElMessage.error(err)
                                console.log(err)
                            })
                    } else {
                        ElMessage.error("请检查输入信息")
                    }
                })
            }
            // 验证码冷却倒计时
            const sendingTimeOut = () => {
                let time = setInterval(() => {
                    if (sendingTime.value === 0)
                        clearInterval(time)
                    else
                        sendingTime.value--
                }, 1000)
            }
            // 邮箱验证码
            const getVerificationCode = () => {
                emailFormItemRef.value.validate("blur", (valid, fields) => {
                    if (valid) {
                        if (getCookie("sendingStatus") === null) {
                            ElMessage({
                                message: '正在发送验证码',
                                type: 'success',
                                duration: 5000,
                                customClass: "loadingMessage",
                                icon: {
                                    template: `
                                        <el-icon class="is-loading" color="#409EFF">
                                            <Loading />
                                        </el-icon>
                                `
                                }
                            })
                            pajax({
                                url: "mail",
                                method: "POST",
                                data: {
                                    email: registerForm.value.email + addressItem.value
                                }
                            })
                                .then(res => {
                                    if (res.code) {
                                        ElMessage.success("验证码发送成功,请前往邮箱查看")
                                        sendingTime.value = 60
                                        setCookie("sendingStatus", "waiting", 60)
                                        sendingTimeOut()
                                    }
                                })
                                .catch(err => {
                                    ElMessage.error(err)
                                    console.log(err)
                                })
                        } else {
                            ElMessage.warning("操作过于频繁,请稍后重试")
                        }
                    } else {
                        ElMessage.error("获取验证码请先正确输入邮箱地址")
                    }
                })
            }
            // 注册ajax请求
            const userRegister = () => {
                registerFormRef.value.validate((valid, fields) => {
                    if (valid) {
                        pajax({
                            url: "register",
                            method: "POST",
                            data: {
                                username: registerForm.value.username,
                                password: registerForm.value.password,
                                email: registerForm.value.email + addressItem.value,
                                verificationCode: registerForm.value.verificationCode
                            }
                        })
                            .then(res => {
                                if (res.code) {
                                    ElMessage.success("注册成功!请登录")
                                    loginForm.value.username = registerForm.value.username
                                    loginForm.value.password = registerForm.value.password
                                    registerFormRef.value.resetFields()
                                    isLoading.value = true
                                    setTimeout(() => {
                                        isLoading.value = false
                                        isRegister.value = true
                                    }, 500)
                                } else
                                    ElMessage.error(res.msg)
                            })
                            .catch(err => {
                                ElMessage.error(err)
                                console.log(err)
                            })
                    } else {
                        ElMessage.error("请检查输入信息")
                    }
                })
            }
            return {
                loginForm,
                registerForm,
                addressItem,
                addressItems,
                loginFormRef,
                registerFormRef,
                emailFormItemRef,
                isRegister,
                isLoading,
                loginRules,
                registerRules,
                sendingTime,
                switchForm,
                userLogin,
                getVerificationCode,
                userRegister,
            }
        }
    }
    const app = Vue.createApp(App)
    app.use(ElementPlus, {
        locale: ElementPlusLocaleZhCn,
    })
    app.component("User", User)
    app.component("Lock", Lock)
    app.component("Message", Message)
    app.component("Promotion", Promotion)
    app.component("Loading", Loading)
    app.mount("#app")
</script>
</body>
</html>
